<template>
  <view class="content">
    <!-- 弹出的卡片 -->
    <u-popup v-model="showHealthInfo" mode="top" height="90%" :mask-close-able="false">
      <view class="info_out">
        <view class="info_within">
          <view class="info_title">
            健康小习惯
          </view>
          <view class="info_content">
            <view class="content_name">
              {{healthInfo.title}}
            </view>
            <image class="content_image" :src="healthInfo.image.path" mode="aspectFit"></image>
            <view class="content_advantage">
              <view class="item_name">
                好处：
              </view>
              <view class="item_content">
                {{healthInfo.benefit}}
              </view>
            </view>
            <view class="content_advantage">
              <view class="item_name">
                动作：
              </view>
              <view class="item_content">
                {{healthInfo.move_content}}
              </view>
            </view>
          </view>
          <view class="info_tip">
            以上内容仅供参考
          </view>
        </view>
        <view v-if="clockCard" class="info_icon animate__animated animate__fadeInBottomRight"
          @click="showHealthInfo=false">
          <u-icon name="close" color="#d6cece" size="30"></u-icon>
        </view>
      </view>
    </u-popup>
    <!-- 轮播信息 -->
    <view class="">
      <u-swiper :list="lunbotuList" name="url" @click="gotoUrl"></u-swiper>
    </view>
    <!-- 各大模块 -->
    <view class="big_box">
      <view class="box">
        <view class="box_title" @click="goto('/pages/record/record')">
          健康档案
        </view>
        <view class="box_title" @click="goto('/pages/article/article?module=健康')">
          健康咨询
        </view>
      </view>
      <view class="mid-box">
        <view v-if="!clocked" class="box_cirle" @click="punchCard">
          打卡
        </view>
        <view v-if="clocked" class="box_cirle">
          已打卡
        </view>
        <!-- <button open-type="getUserInfo" @getuserinfo="getUserInfo">打卡</button> -->
      </view>
      <view class="box">
        <view class="box_title" @click="goto('/pages/article/article?module=运动')">
          运动与健身
        </view>
        <view class="box_title" @click="goto('/pages/foolRecord/foolRecord')">
          饮食记录
        </view>
      </view>
    </view>
    <!-- 论坛 -->
    <view class="comment">
      <mescroll-body ref="mescrollRef" :down="downOption" :up="upOption" @init="mescrollInit" @down="downCallback"
        @up="upCallback">
        <StarPostList :list="postList" :option="postOption" :my_user="vuex_user" @selectPost="selectPost"
          @longpressPost="longpressPost" @clickUserAvatar="clickPostUserAvatar"
          @clickUserNickname="clickPostUserNickname" @clickFocusUser="clickPostFocusUser"
          @clickChatUser="clickPostChatUser" @clickMore="clickMore" @clickSharePost="clickSharePost"
          @clickCommentPost="clickCommentPost" @toggleLike="toggleLikePost">
        </StarPostList>
      </mescroll-body>
      <view class="release-fixed" @click.stop="clickReleasePost">
        +
      </view>
    </view>
  </view>
</template>

<script>
  import MescrollMixin from '@/uni_modules/mescroll-uni/components/mescroll-uni/mescroll-mixins.js'
  import StarPostList from '@/uni_modules/star-community/components/star-post-list/star-post-list.vue'
  import {
    v4 as uuidv4
  } from 'uuid'
  // import mockPost from '../../mock/mockjs/post.js'
  export default {
    mixins: [MescrollMixin], // 使用mixin
    components: {
      StarPostList,
    },
    data() {
      return {
        lunbotuList_real: [],
        clocked: false,
        showHealthInfo: false,
        healthInfo: {},
        clockCard: false,
        //论坛
        postList: [],
        postOption: {
          lineShow: 6, // 文本超出多少行显示省略号
          // iconShare: '/static/share.svg',
          // iconView: '/static/view.svg',
          // iconComment: '/static/comment.svg',
          // iconLike: '/static/like.svg',
          // iconLiked: '/static/liked.svg',
        },
        downOption: {
          use: false, // 不启用mescroll下拉刷新，使用页面原生下拉刷新
        },
        upOption: {
          isBounce: false,
          noMoreSize: 4, // 如果列表已无数据,可设置列表的总数量要大于半页才显示无更多数据;避免列表数据过少(比如只有一条数据),显示无更多数据会不好看; 默认5
          toTop: {
            right: '20rpx',
            bottom: '140rpx',
            safearea: true,
            width: '80rpx',
            radius: '50%',
          }
        },
        userInfo: {}
      }
    },
    computed: {
      lunbotuList() {
        return this.lunbotuList_real.map(item => item.image.url)
      }
    },
    async onLoad() {
      await this.$onLaunched
      let res = await uniCloud.callFunction({
        name: "lunbotu"
      })
      this.lunbotuList_real = res.result.data
      // console.log(this.lunbotuList_real);
      // 创建一个代表当前日期的 Date 对象
      const today = new Date();
      // 设置时间为 00:00:00
      today.setHours(0, 0, 0, 0);
      // 获取时间戳（单位是毫秒）
      const todayTimestamp = today.getTime();
      let res1 = await uniCloud.callFunction({
        name: "punchCard",
        data: {
          flag: 0,
          id: this.vuex_user.id,
          openTime: todayTimestamp
        }
      })
      // console.log(res1.result.data);
      if (res1.result.data.length === 1) {
        this.clocked = true
      }
      //推荐卡片
      uniCloud.callFunction({
        name: "health-card"
      }).then((res) => {
        console.log(res);
        this.healthInfo = res.result.data[0]
        this.showHealthInfo = true
        setInterval(() => {
          this.clockCard = true
        }, 1500)
      })
    },
    onPullDownRefresh() {
      this.mescroll.resetUpScroll()
      setTimeout(function() {
        uni.stopPullDownRefresh();
      }, 1000);
    },
    methods: {
      //打卡
      punchCard() {
        uniCloud.callFunction({
          name: "punchCard",
          data: {
            flag: 1,
            id: this.vuex_user.id,
            openTime: Date.now()
          }
        }).then(res => {
          console.log(res);
          uni.showLoading({
            title: '打卡中'
          });
          setTimeout(function() {
            uni.hideLoading();

            uni.showToast({
              title: '打卡成功',
              icon: 'success'
            })
          }, 1000);
          this.clocked = true
        })
      },
      //条状推文
      gotoUrl(index) {
        console.log(index);
        let type = this.swiList[index].type
        let url = this.swiList[index].url
        if (type == "web") {
          uni.navigateTo({
            url: `/pages/web/web?webUrl=${encodeURIComponent(url)}`
          });
        } else if (type == "pre") {
          uni.previewImage({
            urls: [url]
          })
        } else {
          uni.navigateTo({
            url,
          })
        }

      },
      // // mescroll下拉刷新的回调
      // downCallback() {
      // 	// 这里加载你想下拉刷新的数据, 比如刷新轮播数据
      // 	// loadSwiper();
      // 	// 下拉刷新的回调,默认重置上拉加载列表为第一页 (自动执行 page.num=1, 再触发upCallback方法 )
      // 	this.mescroll.resetUpScroll()
      // },
      // 上拉加载的回调: 其中page.num:当前页 从1开始, page.size:每页数据条数,默认10
      async upCallback(page) {
        try {
          // 请求数据列表
          let list = await this.getPostList(page)
          // 设置列表数据
          if (page.num === 1) this.postList = [] // 如果是第一页需手动制空列表
          this.postList = [...this.postList, ...list] // 追加新数据
          // 联网成功的回调,隐藏下拉刷新和上拉加载的状态
          this.mescroll.endSuccess(list.length)
        } catch (err) {
          console.log(err)
        }
      },
      // 拉取帖子列表
      async getPostList(page) {
        const res = await uniCloud.callFunction({
          name: 'star-community-post',
          data: {
            flag: 3,
            data: {
              my_user_id: 'vuex_user.id',
              status: 1, // 0 审核中 1 正常 2 审核不通过 3 已删除 4 已违规
              sort: {
                createTime: -1
              },
              skip: (page.num - 1) * page.size,
              limit: page.size
            }
          }
        })
        return res.result.data
        // return mockPost.generateRandomPosts(page.size)
      },
      // 选中贴子
      selectPost(post) {
        console.log('selectPost');
        this.goto(`../post-detail/post-detail?id=${post.id}`)
      },
      // 长按帖子
      longpressPost(post) {
        console.log('longpressPost');
        this.showPostMoreActionSheet(post)
      },
      // 点击帖子中的关注用户
      clickPostFocusUser(post) {
        console.log('clickPostFocusUser');
        uni.showToast({
          title: '关注成功'
        })
      },
      // 点击帖子中的私聊用户
      clickPostChatUser(post) {
        console.log('clickPostChatUser')
        uni.showToast({
          title: '私聊界面开发中',
          icon: 'none'
        })
      },
      // 点击帖子更多
      clickMore(post) {
        console.log('clickMore');
        this.showPostMoreActionSheet(post)
      },
      // 点击分享帖子
      clickSharePost(post) {
        console.log('clickSharePost');
      },
      // 点击评论帖子
      clickCommentPost(post) {
        console.log('clickCommentPost');
        // 建议跳转后自动下滑到评论区
        this.goto(`../post-detail/post-detail?id=${post.id}&comment=yes`)
      },
      // 点击帖子用户头像
      clickPostUserAvatar(post) {
        console.log('clickPostUserAvatar');
        this.goto(`../homepage/homepage?id=${post.user_id}`)
      },
      // 点击贴子用户昵称
      clickPostUserNickname(post) {
        console.log('clickPostUserNickname');
        this.goto(`../homepage/homepage?id=${post.user_id}`)
      },
      // 点赞帖子
      async toggleLikePost(post, isLiked) {
        console.log('toggleLikePost', isLiked);

        let vuex_user = this.vuex_user

        if (isLiked) {
          try { // 创建user_id和enmu_id的组合唯一索引
            let insert_like_res = await uniCloud.callFunction({
              name: 'star-community-like',
              data: {
                flag: 1,
                data: {
                  id: uuidv4().replace(/-/g, ''),
                  user_id: vuex_user.id,
                  ta_id: post.user_id,
                  type: 0, // 点赞类型：0帖子，1评论
                  enmu_id: post.id, // 点赞类型对应的id
                }
              }
            })
            console.log(insert_like_res);
            uniCloud.callFunction({
              name: 'star-community-count',
              data: {
                flag: 1,
                data: {
                  id: post.id,
                  likeIncCount: 1
                }
              }
            })
          } catch (e) {
            console.log('重复插入');
          }
        } else {
          let delete_like_res = await uniCloud.callFunction({
            name: 'star-community-like',
            data: {
              flag: 2,
              data: {
                user_id: vuex_user.id,
                enmu_id: post.id, // 点赞类型对应的id
              }
            }
          })
          console.log(delete_like_res.result.data);
          if (delete_like_res.result.data.deletedCount > 0) {
            uniCloud.callFunction({
              name: 'star-community-count',
              data: {
                flag: 1,
                data: {
                  id: post.id,
                  likeIncCount: -1
                }
              }
            })
          }
        }
      },
      // 点击发布帖子按钮
      clickReleasePost() {
        this.goto('../post-release/post-release')
      },
      // 显示帖子更多操作菜单选项
      showPostMoreActionSheet(post) {
        uni.showActionSheet({
          itemList: ['举报'],
          success: (res) => {
            console.log('选中了第' + (res.tapIndex + 1) + '个按钮');
            uni.showToast({
              title: '举报成功'
            })
          },
          fail: (res) => {
            console.log(res.errMsg);
          }
        });
      },
      goto(url) {
        uni.navigateTo({
          url
        })
      }
    }
  }
</script>


<style lang="scss" scoped>
  .info_out {
    width: 100%;
    height: 100%;
    background-color: #85AD6B;
    padding: 40rpx 0 0 40rpx;

    .info_within {
      width: 95%;
      height: 95%;
      background-color: #E8E4CE;
      display: flex;
      flex-direction: column;
      padding: 40rpx 0 30rpx 35rpx;
      position: relative;

      .info_title {
        font-size: 100rpx;
        font-weight: 900;
        color: #F2C108;
        text-align: center;
        margin: 0 0 30rpx 0;
      }

      .info_content {
        width: 95%;
        background-color: #FEFEFA;
        padding: 20rpx 20rpx 30rpx 20rpx;

        .content_name {
          width: fit-content;
          font-size: 30rpx;
          font-weight: 700;
          background-color: #FECC04;
          border-radius: 30rpx;
          padding: 5rpx 20rpx;
          color: #000;
          margin: 0 0 20rpx 0;
        }

        .content_image {
          width: 100%;
          height: 300rpx;
        }

        .content_advantage {
          .item_name {
            color: #fff;
            background-color: #F2AC55;
            width: fit-content;
            font-size: 30rpx;
            font-weight: 700;
            border-radius: 40rpx;
            padding: 5rpx 20rpx;
            margin-bottom: 10rpx;
          }

          .item_content {
            margin-bottom: 10rpx;
            font-weight: 600;
            font-size: 24rpx;
          }
        }
      }

      .info_tip {
        font-size: 20rpx;
        font-weight: 600;
        position: absolute;
        bottom: 10rpx;
        left: 39%;
      }
    }

    .info_icon {
      display: flex;
      justify-content: center;
      align-items: center;
      border-radius: 50%;
      border: 1rpx solid #d6cece;
      position: fixed;
      bottom: -70rpx;
      left: 47%;
      padding: 10rpx;
    }
  }

  .big_box {
    padding-bottom: 30rpx;
    border-bottom: 1rpx solid #888;
    display: flex;
    justify-content: space-around;
    font-size: 35rpx;
    /* height: 180rpx; */
  }

  .box {
    /* height: 110rpx; */
    display: flex;
    flex-direction: column;
    justify-content: space-between;

  }

  .box_cirle {
    border-radius: 100%;
    height: 140rpx;
    width: 140rpx;
    background: #8fcaea;
    color: white;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .box_title {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 90rpx;
    background-color: cornflowerblue;
    color: white;
    margin: 20rpx 0;
    padding: 20rpx;
    border-radius: 20rpx;
  }

  .mid-box {
    display: flex;
    justify-content: center;
    flex-direction: column;
  }

  .comment {
    .release-fixed {
      font-size: 50rpx;
      position: fixed;
      /* #ifdef MP */
      bottom: 50rpx;
      /* #endif */
      /* #ifndef MP */
      bottom: calc(130rpx + constant(safe-area-inset-bottom));
      bottom: calc(130rpx + env(safe-area-inset-bottom));
      /* #endif */
      right: 20rpx;
      background-color: #55aaff;
      color: #fff;
      height: 80rpx;
      width: 80rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      border-radius: 50%;
    }
  }
</style>